<template>
  <div class="wrapper">   
    <div class="container">
      <img src="../../asset/images/背景.png" alt="" class="back">
      <div class="login-box">
        <div class="text-box" v-if="active === 1">
          <img src="../../asset/images/二维码1.png" alt="" class="erweima"  @click="erweiChange">
          <div class="top">
            <p class="title">登录</p>
            <p class="s-title">巡查监管系统</p>
          </div>
          <div class="center" v-if="show">
            <div class="inp-box">
              <span class="mar" @click="regChange">注册</span>
              <span class="mar">忘记密码？</span>
            </div>
            <el-form
              ref="ruleFormRef"
              :model="ruleForm"
              status-icon
              :rules="rules"
              label-width="120px"
              class="demo-ruleForm"
            >
              <el-form-item prop="name" label-width="0">
                  <el-input
                  v-model="ruleForm.name"
                  class="w-50 m-2"
                  placeholder="账号"
                  :prefix-icon="User"
                  />
              </el-form-item>
              <el-form-item prop="pass" label-width="0">
                <el-input
                  v-model="ruleForm.pass"
                  class="w-50 m-2"
                  placeholder="密码"
                  :prefix-icon="Lock"
                  type="password"
                  autocomplete="off" 
                />
              </el-form-item>
              <el-form-item prop="verifycode" label-width="0">
                  <el-input 
                  v-model="ruleForm.verifycode"
                  class="w-50 m-2" 
                  placeholder="验证码" 
                  :prefix-icon="CircleCheck" 
                  />
                  <div @click="refreshCode">
                    <s-identify :identifyCode="identifyCode"></s-identify>
                  </div>
              </el-form-item>
              <div class="inp-box">
                <div class="check-box">
                  <input type="checkbox" name="" id="">&nbsp;记住密码
                </div>
                <span @click="change">短信验证登陆</span>
              </div>
                <el-form-item class="login_btn" label-width="0">
                  <el-button type="primary" @click="loginForm(ruleFormRef)">登录</el-button>
                </el-form-item>
            </el-form>

          </div>
          <div class="center" v-else>
            <div class="inp-box" style="margin-top:12px">
              <span class="mar" @click="change">&lt;&nbsp;账号登陆</span>
            </div>
            <el-form
              ref="ruleFormRef"
              :model="ruleForm"
              status-icon
              :rules="rules"
              label-width="120px"
              class="demo-ruleForm"
            >
            <el-form-item prop="tel" label-width="0">
                  <el-input
                  v-model="ruleForm.tel"
                  class="w-50 m-2"
                  placeholder="手机号"
                  :prefix-icon="User"
                  />
              </el-form-item>
              <el-form-item prop="telmsg" label-width="0">
                <el-input
                  v-model="ruleForm.telmsg"
                  class="w-50 m-2"
                  placeholder="短信验证码"
                  :prefix-icon="CircleCheck"
                />
                <button class="send">发送</button>
              </el-form-item>
              <el-form-item class="login_btn" label-width="0">
                <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
              </el-form-item>
            </el-form>
            
          </div>
        </div>
        <div class="erweima-box" v-else-if="active === 2">
          
            <p  @click="loginChange">&lt;&nbsp;账号登陆</p>          
          <img src="../../asset/images/二维码2.png" alt="">
          <div>扫码登录</div>
        </div>
        <div class="reg-box" v-else>
          <div class="top">
            <p class="title">注册</p>
          </div>
          <div class="center">
            <div class="inp-box" style="margin-top:12px">
              <span class="mar"  @click="loginChange">&lt;&nbsp;账号登陆</span>
            </div>
            <el-form
              ref="ruleFormRef"
              :model="ruleForm"
              status-icon
              :rules="rules"
              label-width="120px"
              class="demo-ruleForm"
            >
            <el-form-item prop="regtel" label-width="0">
                  <el-input
                  v-model="ruleForm.regtel"
                  class="w-50 m-2"
                  placeholder="手机号"
                  :prefix-icon="User"
                  />
              </el-form-item>
              <el-form-item prop="regtelmsg" label-width="0">
                <el-input
                  v-model="ruleForm.regtelmsg"
                  class="w-50 m-2"
                  placeholder="短信验证码"
                  :prefix-icon="CircleCheck"
                />
                <button class="send">发送</button>
              </el-form-item>
              <el-form-item prop="regpass" label-width="0">
                <el-input
                  v-model="ruleForm.regpass"
                  class="w-50 m-2"
                  placeholder="密码"
                  :prefix-icon="Lock"
                  type="password"
                  autocomplete="off" 
                />
              </el-form-item>
              <el-form-item prop="checkpass" label-width="0">
                <el-input
                  v-model="ruleForm.regcheckpass"
                  class="w-50 m-2"
                  placeholder="确认密码"
                  :prefix-icon="Lock"
                  type="password"
                  autocomplete="off" 
                />
              </el-form-item>

                <el-form-item class="login_btn" label-width="0">
                  <el-button type="primary"  @click="submitForm(ruleFormRef)">注册</el-button>
                </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
  </div>
  </div>
</template>
<script setup lang="ts">
import {  reactive, ref ,onMounted} from "vue";
import { User ,Lock , CircleCheck} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import SIdentify from '../identify.vue'
import {loginApi} from '../../api/api'
import { useRouter } from "vue-router";
// const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
  // const input2 = ref('')

const ruleForm = reactive({
  // 账号页面
  name: '',
  pass: '',
  verifycode:'',
  // 短信登录页面
  tel:'',
  telmsg:'',
  // 注册页面
  regtel:'',
  regtelmsg:'',
  regpass: '',
  regcheckpass: '',
})

// 验证码
const identifyCodes = ref('1234567890abcdefghijklmnopqrstuvwxyz')
const identifyCode =ref('')
 /* 自定义验证码规则 */
 const validateVerifycode = (rule :any, value:any, callback:any) => {
      if (value === '') {
      callback(new Error('请输入验证码'))
      } else if (value !== identifyCode.value) {
      console.log('validateVerifycode:', value);
      callback(new Error('验证码不正确!'))
      } else {
      callback()
      }
   }
  const validatetelCheck = (rule :any, value :any, callback :any) => {
        if (!value) {
          return callback(new Error('手机号不能为空'));
        } else {
          const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
          // console.log(reg.test(value));
          if (reg.test(value)) {
            callback();
          } else {
            return callback(new Error('请输入正确的手机号'));
          }
        }
      }
   const validatetelmsgCheck = (rule :any, value :any, callback :any) => {
      if (value === "") {
        return callback(new Error("请输入验证码"));
      } else if (value.length != 4) {
        return callback(new Error("输入正确4位验证码"));
      } else {
        return callback();
      }   
   }

  // 注册页密码校验
  const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (ruleForm.regcheckpass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass', () => null)
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== ruleForm.regpass) {
    callback(new Error("两次输入密码不一致!"))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  // 用户名校验
  name: [
    { required: true, message: '请输入登录名称', trigger: 'blur' },
    { min: 3, max: 10, message: '长度3 - 10个字符', trigger: 'blur' },
  ],
  // 密码校验
  pass: [{ required: true, message: '请输入登录密码', trigger: 'blur' },
    { min: 3, max: 10, message: '长度6 - 15个字符', trigger: 'blur' }
  ],
  verifycode: [{required: true,trigger: 'blur',validator: validateVerifycode,}],
  tel: [{required: true ,trigger: 'blur',validator: validatetelCheck} ],
  telmsg: [{required: true ,trigger: 'blur',validator: validatetelmsgCheck} ],
  regtel: [{required: true ,trigger: 'blur',validator: validatetelCheck} ],
  regtelmsg: [{required: true ,trigger: 'blur',validator: validatetelmsgCheck} ],
  regpass: [{ validator: validatePass, trigger: 'blur' }],
  regcheckpass: [{ validator: validatePass2, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('提交成功!')
    } else {
      console.log('提交失败!')
      return false
      
    }
  })
}

// 切换页面
  let show = ref<Boolean>(true)
  let active =ref<Number>(1)
  const change = () :void => {
    show.value ? show.value = false : show.value = true    
  }
  const loginChange = () :void => {
    if(active.value !== 1) {
      active.value = 1
    }   
  };
  const erweiChange = () :void => {
    if(active.value !== 2) {
      active.value = 2
    }   
  };
  const regChange = () :void => {
    if(active.value !== 3) {
      active.value = 3
    }   
  };



    onMounted(()=>{
      identifyCode.value='';
      makeCode(identifyCodes.value,4);
    //   disableBrowserBack();
    //   history.pushState(null, null, document.URL);
    //   if (window.history && window.history.pushState) {
    //         $(window).on('popstate', function (){
    //             window.history.pushState('forward', null, '');
    //             window.history.forward(1);
    //        });
    //         window.history.pushState('forward', null, '');  //在IE中必须得有这两行
    //         window.history.forward(1);
    // },
    })
    
    const randomNum = (min: any, max:any)=> {
    return Math.floor(Math.random() * (max - min) + min)
   }
   // 切换验证码   
   const refreshCode =()=> {
    identifyCode.value = ''
    makeCode(identifyCodes.value, 4)
   }
   const makeCode= (o :any, l :any)=> {
    for (let i = 0; i < l; i++) {
     identifyCode.value += identifyCodes.value[
      randomNum(0, identifyCodes.value.length)]
    }
    console.log(identifyCode.value)
    /* alert(this.identifyCode) */
   }

  //  登陆请求
  const router = useRouter();// use开头的函数成为hooks，它只能在setup的顶层调用
  const loginForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
      console.log(typeof ruleForm.name);
      console.log(typeof ruleForm.pass);
      
      loginApi({
            username:ruleForm.name,
            password:ruleForm.pass    
        }).then(res => {
          console.log(res);
          let code = res.data.meta.status
          // console.log(code);
          if(code == '200'){
            router.push('/home');
            console.log('登录成功');
            const num = res.data.user.num
            const username = res.data.user.username
            const password = res.data.user.password
            const token = res.data.user.token
            console.log(num);
            // const obj = {'username':username,'pasword':password,'num':num}
            // sessionStorage.setItem('obj', JSON.stringify(obj))
            sessionStorage.setItem('num', num)
            sessionStorage.setItem('username', username)
            sessionStorage.setItem('password', password)
            sessionStorage.setItem('token', token)
            // sessionStorage.setItem('num',num)  
          }else {
            alert('用户名或密码错误')
          }
        })
    } else {
      console.log('error submit!')
      return false
    }
  })
}

</script>

<style lang="less" scoped>

  .container {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
    .back {
      width: 100%;
      height: 100%;
    }
    .reg-box ,.text-box {
      width: 100%;
      height: 100%;
      position: relative;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      .erweima {
        position: absolute;
        top: 8px;
        right: 8px;
        width: 80px;
        height: 80px;
        cursor: pointer;
      }
    }
    .erweima-box {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      img {
        width: 40%;
      }
      p {
        line-height: 26px;
        width: 40%;
        cursor: pointer;
        &:hover {
          color: #364582;
        }
      }
      div {
        line-height: 40px;
      }
    }
  .login-box {
    position: absolute;
    left: 50%;
    top: 140px;
    width: 40%;
    height: 350px;
    background-color: rgba(255, 255, 255, 0.4);
    border-radius: 14px;
    transform: translateX(-20%);
    
    color: #FFFFFF;
    
    .top {
        font-family: Adobe Heiti Std;
        font-weight: normal;
        text-align: center;
        margin-bottom: 6px;
        .title {
          font-size: 16px;
          line-height: 24px;

        }       
        .s-title {
          font-size: 12px;
          line-height: 20px;
          color: #D1D9E6;
        }
    }
    .center {
      display: flex;
      flex-direction: column;
      width: 50%;
      :deep(.el-form-item__content) {
        margin-left: 0;
        flex-wrap: nowrap;
        line-height: 14px;
      }
      .el-input {
        width: 100%;
        font-size: 12px;
      }
      .el-button {
        margin-top: 20px;
        width: 100%;
        background-color: #142b87;
        border: none;
        &:hover {
          background-color: #364582;
        }
      }
      .inp-box {
        width: 100%;
        display: flex;
        justify-content: space-between;
        img {
          display: block;
          width: 8px;
          height: 8px;
          margin-right: 3px;
        }
        
        .code {
          display: block;
          width: 33%;
          height: 26px;
          background-color: #FFFFFF;
          color: #6379A2 ;
          font-size: 18px;
          text-align: center;
          line-height: 26px;
        }
        .check-box {
          display: flex;
          align-items: center;
        }
        span {
          cursor: pointer;
          &:hover {
            color: #364582;
          }
        }
      }
    }
    .send {
      width: 45px;
      height: 30px;
      background-color: #364582;
      color: #fff;
      margin-left: 5px;
      border: none;
      border-radius: 2px;
    }
  }
 }
.mar {
  display: block;
  margin-left: 10px;
  margin-bottom: 4px;
}
input::placeholder {
  color: #fff;
  font-size: 12px;
}



</style>